import Taro from '@tarojs/taro'

const BASE_URL = 'https://dy.ttentau.top'

const TIME_OUT = 10000

interface RequestConfig {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  config?: Record<string, any>
}

export class Request {
  private baseUrl: string
  private timeout: number
  constructor(baseUrl = BASE_URL, timeout = TIME_OUT) {
    this.baseUrl = baseUrl
    this.timeout = timeout
  }

  request<T>({ url, method, data, config }: RequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (process.env.TARO_ENV === 'h5') {
        fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
            ...config,
          },
          body: method !== 'GET' ? JSON.stringify(data) : undefined,
        })
          .then(res => {
            console.log(res, 13123123)
            res.json().then(data => resolve(data as T))
          })
          .catch(err => {
            reject(err)
          })
      } else {
        Taro.request({
          url: `${this.baseUrl}${url}`,
          data: {
            ...data,
          },
          method,
          timeout: this.timeout,
          header: {
            'Content-Type': 'application/json',
            ...config,
          },
        })
          .then(res => {
            resolve(res.data as T)
          })
          .catch(err => {
            reject(err)
          })
      }
    })
  }

  get<T>(url: string, data?: any, config?: Record<string, any>) {
    return this.request<T>({ url, data, method: 'GET', config })
  }

  post<T>(url: string, data?: any, config?: Record<string, any>) {
    return this.request<T>({ url, data, method: 'GET', config })
  }

  put<T>(url: string, data?: any, config?: Record<string, any>) {
    return this.request<T>({ url, data, method: 'GET', config })
  }

  delete<T>(url: string, data?: any, config?: Record<string, any>) {
    return this.request<T>({ url, data, method: 'GET', config })
  }
}

export const request = new Request()

export default request
